package cn.kgc.novel.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.kgc.novel.common.ErrorCodeEnum;
import cn.kgc.novel.common.Result;
import cn.kgc.novel.pojo.Books;
import cn.kgc.novel.pojo.Bookshelf;
import cn.kgc.novel.pojo.Users;
import cn.kgc.novel.service.UsersService;
import cn.kgc.novel.utils.JWTUtil;
import cn.kgc.novel.utils.SendEmail;
import com.dtflys.forest.annotation.Get;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.dromara.sms4j.comm.utils.SmsUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

//杨将
@RestController
@CrossOrigin
public class UsersController {
    @Resource
    private SendEmail sendEmail;
    @Resource
    private UsersService usersService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate<String,Object> RedisTemplate;

    final String defaultuseravatar = "https://wulong01.oss-cn-beijing.aliyuncs.com/novel/%E5%AD%A6%E5%A7%90%E5%88%AB%E6%80%95%E6%88%91%E6%9D%A5c.jfif";
    //更据类型来拿小说
    @GetMapping("/selectz")
    public Result selectz(Integer pageNum,String sex,String category,String status,String num,String redu){
        System.out.println("pageNUM:"+pageNum);
        List<Users> users=null;
        PageHelper.startPage(pageNum,9);
        PageInfo<Users> pageInfo = null;
        int i = 0;
        if(sex.equals("全部")){
            sex="";
        }
        if(category.equals("全部")){
            category="";
        }
        if(status.equals("全部")){
            status="";
        }
        if (num.equals("30万以下")){
            num="20";
        }else if (num.equals("30-50万")){
            num="40";
        }else if(num.equals("50-100万")){
            num="70";
        }else if (num.equals("100-200万")){
            num="150";
        }else if (num.equals("200万以上")){
            num="210";
        }else {
            num="";
        }
        if (redu.equals("字数")) {
            users = usersService.selectx1(sex, category, status, num);
        }else if (redu.equals("最新")){
            users =usersService.selectx2(sex, category, status, num);
        }else{
            users = usersService.selectx3(sex, category, status, num);
        }
        pageInfo = new PageInfo<>(users);
        return Result.ok(pageInfo);
    }
    //根据小说名查作者
    @GetMapping("/checktheauthor")
    public Result checktheauthor(String bookname){
        List<Users> checktheauthor = usersService.checktheauthor(bookname);
        return Result.ok(checktheauthor);
    }
    //根据作者查询小说
    @GetMapping("/novelauthorname")
    public Result novelauthorname(String name){
        List<Users> novelauthorname = usersService.novelauthorname(name);
        return Result.ok(novelauthorname);
    }
    //查询作者和书名
    @GetMapping("/showselectzz")
    public Result showselectzz(){
        List<Users> flieshow = usersService.flieshow();
        return Result.ok(flieshow);
    }
    @GetMapping("/login")
    public Result login(){
        return Result.ok();
    }
    //查询所有user
    @GetMapping("/find")
    public Result findUsersList(
            Users users,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize
    ){
        PageHelper.startPage(pageNum,pageSize);
        List<Users> usersList = usersService.findList(users);
        PageInfo<Users> pageInfo=new PageInfo<Users>(usersList);
        return Result.ok(pageInfo);
    }
    //通过id查user
    @GetMapping("/getById")
    public Result getById(Integer uid){
        Users user=usersService.findById(uid);
        String password = user.getPassword();
        String phone = user.getPhone();
        String email = user.getEmail();
        String password1 = DesensitizedUtil.password(password);
        String phone1 = DesensitizedUtil.mobilePhone(phone);
        String email1 = DesensitizedUtil.email(email);
        user.setPassword(password1);
        user.setPhone(phone1);
        user.setEmail(email1);
        return Result.ok(user);
    }
    //修改信息
    @PostMapping(value = "/update")
    public Result update(@RequestBody Users users){
        try {
            usersService.edit(users);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }
    @PostMapping("/test")
    public void test(@RequestBody Users users){
        System.out.println(users);
    }
    //注册
    @PostMapping(value = "/register")
    public Result register(@RequestBody Users users){
        System.out.println("users:"+users);
        usersService.register(users);
        int uid = usersService.findByAccount(users.getAccount()).getUid();
        usersService.regMongo(uid);
//        historyUser.setId(users1.getUid());
//        mongoTemplate.save(historyUser);
        return Result.ok();
    }

    //删除
    @PostMapping(value = "/delete")
    public Result delete(Integer uid){
        usersService.delete(uid);
        return Result.ok();
    }
    //通过账号查找user
    @GetMapping(value = "/getByAccount")
    public Result getByAccount(String account){
        Users users=usersService.findByAccount(account);
        return Result.ok(users);
    }
    //通过uid,bid来查看历史阅读记录(返回值如果是0,就是没有阅读)
    @GetMapping(value = "/getHistById")
    public Result getHistById(int uid,int bid){
        int cid=usersService.getHistById(uid,bid);
        return Result.ok(cid);
    }
    //添加历史阅读记录
    @PostMapping(value = "/addHis")
    public Result addHis(int uid,int bid,int cid){
        usersService.addHis(uid,bid,cid);
        return Result.ok();
    }
    //修改历史记录
    @PostMapping(value = "/updateHis")
    public Result updateHis(int uid,int bid,int cid){
        usersService.updateHis(uid,bid,cid);
        return Result.ok();
    }
    //判读都没读过，读过修改，没读过添加，武龙
    @GetMapping("/History")
    public Result addfindupdate(int uid,int bid,int cid){
        Result histById = this.getHistById(uid, bid);
        Integer data = (Integer)histById.getData();
        if(data.equals(0)){
            System.out.println("没有读过，添加历史记录");
            this.addHis(uid,bid,cid);
        }else {
            System.out.println("读过，修改历史记录");
            this.updateHis(uid,bid,cid);
        }
        return Result.ok();
    }
    //查看是否加入书架(返回值如果是0则未加入书架,1已加入书架 )
    @GetMapping(value = "/findShelf")
    public Result findShelf(int uid,int bid){
        int shelf = usersService.findShelf(uid, bid);
        return Result.ok(shelf);
    }
    //加入书架
    @PostMapping(value = "/addShelf")
    public Result addShelf(int uid,int bid){
        usersService.addShelf(uid,bid);
        return Result.ok();
    }
    //移除书架
    @PostMapping(value = "/delShelf")
    public Result delShelf(int uid,int bid){
        usersService.delShelf(uid,bid);
        return Result.ok();
    }


    //用户登录
    @GetMapping(value = "/logintwo")
    public Result logintwo(String phone, String account,String password,String code){
        Users user = usersService.logintwo(phone,account,password);
        Object redisvalue = null;
        Long expire = null;
        if(user==null&&account==null&&phone!=null){
            System.out.println("进入了if里面");
            Users user1 = new Users();
            user1.setPhone(phone);
            user1.setUseravatar(defaultuseravatar);
            String name1 = "用户";
            String name2 = name1+UUID.randomUUID().toString().substring(0,5);
            user1.setName(name2);
            user1.setPhone(phone);
            user1.setAccount(phone);
            user1.setProfile("暂无简介");
            user1.setPermissions("1");
            usersService.register(user1);
            user =usersService.logintwo(phone,null,null);
            System.out.println("新增的用户"+user);
            int uid = usersService.findByAccount(user.getAccount()).getUid();
            System.out.println("新增的uid"+uid);
            usersService.regMongo(uid);
        }else {
//            if(!(user.getPermissions().equals("3")||user.getPermissions().equals("4"))){
                String key = "uid"+user.getUid();
                redisvalue = RedisTemplate.opsForValue().get(key);
                if(redisvalue!=null){
                    expire = RedisTemplate.getExpire(key, TimeUnit.DAYS);
                }else if(user.getPermissions().equals("0")){
                    usersService.updatePermissionspt(user.getName(),user.getUid().toString());
                }
//            }

        }
        String yanzhengma= null;
        if(phone!=null){
           yanzhengma = stringRedisTemplate.opsForValue().get("yanzhengma");
        }

        String token = null;
        if(password!=null){
            token = JWTUtil.getToken(user.getUid().toString(),user.getPassword());
        }
        Object[] userandtoken = new Object[2];
        userandtoken[0] = user;
        userandtoken[1] = token;
        if(redisvalue==null){
            if(phone!=null&&code.equals(yanzhengma)&&account==null){
                return Result.ok(userandtoken);
            }else if(account!=null&&password!=null){
                return Result.ok(userandtoken);
            }else {
                return Result.error(ErrorCodeEnum.YZM_ERROR);
            }
        }else {
            return Result.error(666,"该账号已被封禁"+expire+"天");
        }

    }



    //用户注册
    @PostMapping(value="/registertwo")
    public Result registertwo(String phone,String password){
        usersService.registertwo(phone,password);
        return Result.ok();
    }

    //查询
    @GetMapping(value = "/findtwo")
    public Result find(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "2") Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Users> usersList = usersService.find();
        PageInfo<Users> pageInfo = new PageInfo<>(usersList);
        return  Result.ok(pageInfo);
    }
    //修改密码--武龙
    @GetMapping("/updatepassword")
    public Result updatepassword(String phone,String newpassword){
        int result = usersService.updatepassword(phone,newpassword);
        if(result==1){
            return Result.ok();
        }else {
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }

    }

    //2023-11-21 查询管理员
    @GetMapping(value = "/findAdmin")
    public Result findAdmin(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "10") Integer pageSize,
                            String name)
    {
        PageHelper.startPage(pageNum,pageSize);
        List<Users> adminList = usersService.findAdmin(name);
        PageInfo<Users> pageInfo = new PageInfo<>(adminList);
        return Result.ok(pageInfo);
    }
    //2023-11-21 添加管理员
    @PostMapping(value = "/addAdmin")
    public Result addAdmin(@RequestBody Users admin){
        System.out.println(admin.getAccount()+"\t"+admin.getPassword());
        String name = "管理员"+ SmsUtil.getRandomInt(6);
        admin.setName(name);
        usersService.addAdmin(admin);
        return Result.ok();
    }
    //2023-11-21 删除管理员
    @PostMapping(value = "/deleteAdmin")
    public Result deleteAdmin(Integer uid){
        usersService.deleteAdmin(uid);
        return Result.ok();
    }

    //新加的
//从普通用户成为作者
    @PostMapping("/updatePermissionszz")
    public Result updatePermissionszz(String name){
        try {
            usersService.updatePermissionszz(name);
            return Result.ok("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }
    //从普通用户到待审核
    @PostMapping("/UpdatePermissionsdsh")
    public Result UpdatePermissionsdsh(String name){
        System.out.println(name);
        try {
            usersService.UpdatePermissionsdsh(name);
            return Result.ok("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }
    //从普通用户到封禁
    @PostMapping("/UpdatePermissionsdfj")
    public Result UpdatePermissionsdfj(String name,String uid,String email){
        try {
            usersService.UpdatePermissionsdfj(name,uid);
            String subject = "锦途小说网";
            String text ="由于您违反了用户协议,对您的账号做出了封禁180天处理,如有问题请联系我们管理员";
            sendEmail.sendSimpleEmail(email,subject,text);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }
    //从封禁到用户到普通用户

    @PostMapping("/updatePermissionspt")
    public Result updatePermissionspt(String name,String uid,String email){
        try {
            usersService.updatePermissionspt(name,uid);
            String subject = "锦途小说网";
            String text ="恭喜您,您的锦途小说网账号已被解封,给您带来的不便敬请谅解";
            sendEmail.sendSimpleEmail(email,subject,text);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }

    // 2023-11-23 查询所有待审核的用户
    @GetMapping("/selectdsh")
    public Result selectdsh(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "5") Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Users> selectdsh = usersService.selectdsh();
        PageInfo<Users> pageInfo=new PageInfo<Users>(selectdsh);
        return Result.ok(pageInfo);
    }

}
